#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
进度条组件 - 显示批量操作进度
"""

import tkinter as tk
from tkinter import ttk
import ttkbootstrap as ttk_bs
from ttkbootstrap.constants import *
import threading
import time
from typing import Callable, Optional
from utils.logger import get_logger


class ProgressWidget:
    """进度条组件"""
    
    def __init__(self, parent, title: str = "操作进度"):
        self.parent = parent
        self.title = title
        self.logger = get_logger("ProgressWidget")
        
        # 状态变量
        self.is_cancelled = False
        self.current_step = 0
        self.total_steps = 0
        
        # 创建进度窗口
        self.progress_window = None
        self.progress_var = None
        self.progress_bar = None
        self.status_var = None
        self.cancel_callback = None
    
    def show_progress(self, total_steps: int, cancel_callback: Optional[Callable] = None):
        """显示进度窗口"""
        self.total_steps = total_steps
        self.current_step = 0
        self.is_cancelled = False
        self.cancel_callback = cancel_callback
        
        # 创建模态窗口
        self.progress_window = tk.Toplevel(self.parent)
        self.progress_window.title(self.title)
        self.progress_window.geometry("500x200")
        self.progress_window.transient(self.parent)
        self.progress_window.grab_set()
        
        # 居中显示
        self.progress_window.update_idletasks()
        x = (self.progress_window.winfo_screenwidth() // 2) - (500 // 2)
        y = (self.progress_window.winfo_screenheight() // 2) - (200 // 2)
        self.progress_window.geometry(f"500x200+{x}+{y}")
        
        # 防止关闭窗口
        self.progress_window.protocol("WM_DELETE_WINDOW", self._on_window_close)
        
        # 创建UI
        main_frame = ttk_bs.Frame(self.progress_window, padding=20)
        main_frame.pack(fill=BOTH, expand=True)
        
        # 标题
        title_label = ttk_bs.Label(
            main_frame, 
            text=self.title,
            font=("Microsoft YaHei", 12, "bold")
        )
        title_label.pack(pady=(0, 20))
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk_bs.Progressbar(
            main_frame,
            variable=self.progress_var,
            maximum=100,
            bootstyle=INFO,
            length=400
        )
        self.progress_bar.pack(pady=(0, 10))
        
        # 状态文本
        self.status_var = tk.StringVar(value="准备开始...")
        status_label = ttk.Label(main_frame, textvariable=self.status_var)
        status_label.pack(pady=(0, 20))
        
        # 按钮框架
        button_frame = ttk.Frame(main_frame)
        button_frame.pack(fill=X)
        
        # 取消按钮
        if cancel_callback:
            self.cancel_btn = ttk_bs.Button(
                button_frame,
                text="取消操作",
                bootstyle=DANGER,
                command=self._on_cancel,
                width=15
            )
            self.cancel_btn.pack(side=RIGHT)
        
        # 最小化按钮
        ttk_bs.Button(
            button_frame,
            text="最小化",
            bootstyle=SECONDARY,
            command=self.progress_window.iconify,
            width=15
        ).pack(side=LEFT)
        
        self.logger.info(f"进度窗口已显示，总步数: {total_steps}")
    
    def update_progress(self, current_step: int, status_text: str = ""):
        """更新进度"""
        if self.progress_window and self.progress_window.winfo_exists():
            self.current_step = current_step
            
            # 计算进度百分比
            if self.total_steps > 0:
                progress_percent = (current_step / self.total_steps) * 100
                self.progress_var.set(progress_percent)
            
            # 更新状态文本
            if status_text:
                display_text = f"({current_step}/{self.total_steps}) {status_text}"
                self.status_var.set(display_text)
            
            # 更新UI
            self.progress_window.update()
            
            self.logger.debug(f"进度更新: {current_step}/{self.total_steps} - {status_text}")
    
    def set_status(self, status_text: str):
        """设置状态文本"""
        if self.progress_window and self.progress_window.winfo_exists():
            self.status_var.set(status_text)
            self.progress_window.update()
    
    def complete(self, success_message: str = "操作完成！"):
        """完成进度"""
        if self.progress_window and self.progress_window.winfo_exists():
            self.progress_var.set(100)
            self.status_var.set(success_message)
            
            # 延迟关闭
            self.progress_window.after(2000, self.close)
            
            self.logger.info(f"进度完成: {success_message}")
    
    def close(self):
        """关闭进度窗口"""
        if self.progress_window and self.progress_window.winfo_exists():
            self.progress_window.grab_release()
            self.progress_window.destroy()
            self.progress_window = None
            
            self.logger.info("进度窗口已关闭")
    
    def _on_cancel(self):
        """取消按钮点击事件"""
        self.is_cancelled = True
        self.set_status("正在取消操作...")
        
        if self.cancel_callback:
            threading.Thread(target=self.cancel_callback, daemon=True).start()
        
        self.logger.info("用户取消了操作")
    
    def _on_window_close(self):
        """窗口关闭事件"""
        # 阻止直接关闭窗口，只能通过取消按钮
        pass


class BatchProgressManager:
    """批量操作进度管理器"""
    
    def __init__(self, parent):
        self.parent = parent
        self.logger = get_logger("BatchProgressManager")
        self.progress_widget = None
        self.is_cancelled = False
    
    def start_batch_operation(self, operation_name: str, total_count: int):
        """开始批量操作"""
        self.is_cancelled = False
        self.progress_widget = ProgressWidget(self.parent, f"{operation_name}")
        self.progress_widget.show_progress(total_count, self._on_cancel)
        
        self.logger.info(f"开始批量操作: {operation_name}, 总数: {total_count}")
        return self.progress_widget
    
    def update_item(self, current_index: int, item_name: str, status: str):
        """更新单项进度"""
        if self.progress_widget:
            status_text = f"{status} '{item_name}'"
            self.progress_widget.update_progress(current_index, status_text)
    
    def complete_operation(self, success_count: int, fail_count: int):
        """完成操作"""
        if self.progress_widget:
            message = f"操作完成！成功: {success_count} 个，失败: {fail_count} 个"
            self.progress_widget.complete(message)
        
        self.logger.info(f"批量操作完成 - 成功: {success_count}, 失败: {fail_count}")
    
    def complete_batch_operation(self, success_count: int, fail_count: int):
        """完成批量操作（别名方法）"""
        self.complete_operation(success_count, fail_count)
    
    def cancel_operation(self):
        """取消操作"""
        self.is_cancelled = True
        if self.progress_widget:
            self.progress_widget.close()
        
        self.logger.info("批量操作已取消")
    
    def _on_cancel(self):
        """取消回调"""
        self.is_cancelled = True


# 进度装饰器
def with_progress(operation_name: str):
    """进度装饰器 - 自动显示操作进度"""
    def decorator(func):
        def wrapper(self, *args, **kwargs):
            # 获取操作数量
            if hasattr(self, 'selected_repos'):
                total_count = len(self.selected_repos)
            else:
                total_count = 1
            
            if total_count == 0:
                return func(self, *args, **kwargs)
            
            # 创建进度管理器
            progress_manager = BatchProgressManager(self)
            progress_widget = progress_manager.start_batch_operation(operation_name, total_count)
            
            try:
                # 执行原函数
                result = func(self, progress_manager, *args, **kwargs)
                return result
            except Exception as e:
                progress_widget.set_status(f"操作失败: {str(e)}")
                progress_widget.close()
                raise
        
        return wrapper
    return decorator
